import { AfterViewChecked, Component, OnInit, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { MainTaskServiceProxy, MainTaskGoProductionDto, BatchBoundTechDocInput, ReceiveTaskInput, TaskDto, NameValueDtoOfNameValueDto, PipelineServiceProxy, PipelineNodesServiceProxy, OrganizationUnitServiceProxy, TechDocServiceProxy, PipelineListDto, SimpleTechDocDto, TechDocDto, BatchBoundTech } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';

import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { MenuItem } from 'primeng/api';
import * as moment from 'moment';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import { ComboboxItemDto } from '@shared/service-proxies/ztdevice-service-proxies';


@Component({
  selector: 'batchIntoStepModal',
  templateUrl: './batch-into-step.component.html',
  //styleUrls: ['./flowapplyordinarycreate.component.css']
})

export class BatchIntoStepComponent extends AppComponentBase implements OnInit {


  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('selectpaginator') selectpaginator: Paginator;
  @ViewChild('taskdataTable') taskdataTable: Table;
  @ViewChild('selectdataTable') selectdataTable: Table;
  selectPrimengTableHelper: PrimengTableHelper;
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  filterText = '';
  code = '';
  active = false;
  saving = false;
  runing = false;
  selected: any[];
  receiveTasks = new Array<ReceiveTaskInput>();
  dueDate = new Date();
  index = 1;

  order: TaskDto = new TaskDto();
  mainTaskGoProductionList = new Array<MainTaskGoProductionDto>();
  Outsourcings;
  cols: any[];
  tmpls: NameValueDtoOfNameValueDto[];
  tmplName = '';
  pipe: PipelineListDto = new PipelineListDto();
  pipe1: PipelineListDto = new PipelineListDto();
  techDocs = new Array<SimpleTechDocDto>();
  selectedTechDoc = new SimpleTechDocDto();
  tabs: MenuItem[];
  techDocView = new TechDocDto();
  oldTechDocView = new TechDocDto();

  teamGroups: ComboboxItemDto[] = [];
  teamGroupName = '' ;
  datas: any[];
  constructor(injector: Injector,

    private _mainTaskServiceProxy: MainTaskServiceProxy,
    private _pipelineService: PipelineServiceProxy,
    private _taskServiceProxy: PipelineNodesServiceProxy,
    private _organization: OrganizationUnitServiceProxy,
    private _techDocServiceProxy: TechDocServiceProxy,

  ) {
    super(injector);
    this.selectPrimengTableHelper = new PrimengTableHelper();
  }

  ngOnInit () {
     this.getTabs();
  }

getTabs() {
    this.tabs = [
        { label: '任务列表', icon: 'fa fa-fw fa-bar-chart' , style : 1 },
        { label: '待绑定任务列表', icon: 'fa fa-fw fa-calendar', style : 2 },
        {label: '工艺规程', icon: 'fa fa-fw fa-calendar', style : 3}
    ];
}
tabTypeClick(tab: any, index) {
      this.index = index;
}
  show(): void {
    this.active = true;
    this.selected = [];
    this.selectPrimengTableHelper.records = this.selected;
    this.selectPrimengTableHelper.totalRecordsCount = 0;
    this._pipelineService.getPipelineTmpls()
      .subscribe((result) => {
        this.tmpls = result.items;
        this.getPipes();
      });

    this.modal.show();
  }

  rowSelect(event: any) {

    let rowData = event.data;
    this._techDocServiceProxy.getTechDocForView(rowData.codeId).subscribe(result => {
      this.techDocView = result;
    });
  }
  save(): void {


    let pipeLines = [];
    for (let i = 0; i < this.selected.length; i++) {
      pipeLines.push(this.selected[i].id);

    }
    this.saving = true;
    this._pipelineService.getPipelineAndRunOfBatch(pipeLines)

      .subscribe(() => {
        this.notify.info('运行成功');
        this.close();
        this.modalSave.emit(null);
      });
    this.close();



  }
  close(): void {
    this.active = false;
    this.primengTableHelper.records = null;
    this.filterText = '';
    this.selected = [];
    this.mainTaskGoProductionList = [];
    this.datas = [];
    this.techDocs = new Array<SimpleTechDocDto>();
    this.techDocView = new TechDocDto();
    this.oldTechDocView = new TechDocDto();
    this.index = 1;
    this.modal.hide();
  }




  getPipes(event?: LazyLoadEvent) {
    this._pipelineService.getPipelinesForNode(
      this.filterText,
      '58',
      'GY1工艺校验',
      '',
      this.primengTableHelper.getMaxResultCount(this.paginator, event),
      this.primengTableHelper.getSkipCount(this.paginator, event)

    )
      .subscribe(result => {
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
       // this.pipe1 = this.primengTableHelper.records[0];

      });
  }

  joinTask(pipe) {
    if (this.selected.length === 0) {
      this.selected.push(pipe);
      this.notify.success('当前管道加入成功');

    } else {
        for (let i = 0; i < this.selected.length; i++) {
            // let keepGoing = false;
            if (this.selected.indexOf(pipe) === -1) {
                if (
                    pipe.id !== this.selected[i].id
                 ) {
                    this.selected.push(pipe);
                    this.notify.success('当前管道加入成功');
                    break;
                }
            } else {
                this.notify.error('当前管道已添加');
            }
        }
    }

  }
getCode() {
    this._techDocServiceProxy.getSimpleTechDocsByRef(this.code, '58')
    .subscribe(result => {
      this.techDocs = result.items;
    });
}




  //获取要投产的任务列表
  getModels1() {
    this.selectPrimengTableHelper.records = this.selected;
    this.selectPrimengTableHelper.totalRecordsCount = this.selected.length;
    this.selectPrimengTableHelper.hideLoadingIndicator();

  }
  deletePipe(pipe) {
    for (let i = 0; i < this.selected.length; i++) {
      if ( this.selected[i].id === pipe.id ) { this.selected.splice(i, 1); }
    }

  }
  //批量绑定工艺
  batchBoundTechDoc() {
    let tt = new BatchBoundTechDocInput();
    let batchBoundTechlist = new Array<BatchBoundTech>();
    for (let i = 0; i < this.selected.length; i++) {

      let batchBoundTech = new BatchBoundTech();

      batchBoundTech.pipeId = this.selected[i].id;
      batchBoundTech.techDocCode = this.selectedTechDoc.codeId;
      batchBoundTechlist.push(batchBoundTech);
    }
    tt.batchBoundTech = batchBoundTechlist;

    this._taskServiceProxy.batchBoundTechDoc(tt)
      .subscribe(result => {
        this.notify.success( '绑定成功');

      });
  }

}
